package com.mobi.spring1.controller;

import com.mobi.spring1.Sever.impl.UserSever;
import com.mobi.spring1.pojo.User;
import io.swagger.annotations.Api;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;

@Api(tags = "学生控制类")
@Controller
@RequestMapping("/user")
class UserController {

    @GetMapping("/hello")
    @ResponseBody
    public Map<String, Object> showHelloWorld(){
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "HelloWorld");
        return map;
    }


    @Autowired
    private UserSever us;


    //添加学生
    @GetMapping("/add")
    @ResponseBody
    public void add(HttpServletResponse response, HttpServletRequest request){
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

//        user.setName(username);
//        user.setSex(sex);
//        user.setWechat(WeChat);
//        user.setTelephone(Integer.parseInt(telephone));
//        user.setAddress(address);
        us.add(user);
        try {
            response.sendRedirect("/chose_student_list.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //删除学生
    @GetMapping("/del")
    @ResponseBody
    public void del(@Param("id") Integer id , HttpServletResponse response){
        us.del(id);
        try {
            response.sendRedirect("/chose_student_list.html");//重定向页面
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/upd")
    @ResponseBody
    public void upd(@RequestBody User user){
        us.add(user);
    }

    @GetMapping("/findById")
    @ResponseBody
    public Map<String, Object> findById(@RequestBody Integer id){
        Map<String, Object> map = new HashMap<>();
        Object byId = us.findById(id);
        map.put("findById",byId);
        return map;
    }

    @GetMapping("/findAll")
    @ResponseBody
    public Map<String, Object> findAll(){
        Map<String, Object> map = new HashMap<>();
        System.out.println(us);
        map.put("findAllUser",us.findAll());
        return map;
    }
}
